package netty.nio;

import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
import lombok.val;
import sun.nio.ch.FileChannelImpl;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author: zhangrongqing
 * @Date: 2020/1/6 14:33
 */
public class FileChannelDemo {
    public static void writeFile() throws IOException{
        byte[] bytes = "hello world".getBytes();

//        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put(bytes);

        //如果使用put操作一定要重置buffer的标识位
        buffer.flip();

        FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\zhang.rongqing\\Desktop\\test.txt");
        FileChannel fileChannel =  fileOutputStream.getChannel();

        fileChannel.write(buffer);

        fileChannel.close();
    }

    public static void readFile() throws IOException{

        FileInputStream fileInputStream = new FileInputStream("C:\\Users\\zhang.rongqing\\Desktop\\test.txt");
        FileChannel channel = fileInputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        channel.read(byteBuffer);

        byteBuffer.flip();

        System.out.println(new String(byteBuffer.array()));

//        while (byteBuffer.hasRemaining()){
//            System.out.println(byteBuffer.get());
//        }

        channel.close();

    }

    public static void main(String[] args)  {
        try {
            FileChannelDemo.readFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
